package ru.ognick.coachsystem.common;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import android.util.Log;


public class Training implements Serializable {
	private static final long serialVersionUID = 6066611998496838078L;
	public static final String TAG = "Training";
    public static final Gson gson = (new GsonBuilder()).create();

    
	private File filename = null;
	private String about = null;
	private ArrayList<Exercise> exercises = new ArrayList<Exercise>();
	
	public Training(String filename){
		this.filename = IOFile.touchFile(filename);
		save();
	}
	
	public static Training load (File file){
		try {
			String text = IOFile.loadTextFile(file);
			JSONObject jsonObject = new JSONObject(text);
			Training self = gson.fromJson(jsonObject.toString(), Training.class);
			self.filename = file;
			return self;
		} catch (IOException e) {
			Log.e (TAG, e.getMessage());
		} catch (JSONException e) {
			Log.e (TAG, e.getMessage());
		}
		return null;
	}
	
	public boolean save() {
		File file = getFilename();
		
		try {
			String text = gson.toJson(this);
			IOFile.saveTextFile(file, text);
			return true;
		} catch (IOException e) {
			Log.e (TAG, e.getMessage());
		}
		return false;
	}
	
	public boolean delete() {
		return IOFile.removeFile(getFilename());
	}

	public ArrayList<Exercise> getExercises() {
		return exercises;
	}

	public File getFilename() {
		return filename;
	}

	public void setAbout(String about) {
		this.about = about;
	}

	public String getAbout() {
		return about;
	}   
}
